package com.gitpractice.liwushuo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.gitpractice.liwushuo.contanst.UrlString;
import com.gitpractice.liwushuo.fragment.CategoryFragment;
import com.gitpractice.liwushuo.fragment.HomeFragment;
import com.gitpractice.liwushuo.fragment.ProfileFragment;
import com.gitpractice.liwushuo.fragment.SelectFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    /**
     * 导入
     * compile 'com.jakewharton:butterknife:6.1.0'
     * compile 'com.android.support:design:24.0.0'
     */
    @butterknife.InjectView(R.id.rg_home)
    RadioGroup mRadioGroup;

    private int lastCheckedIndex;
    private List<Fragment> mFragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        butterknife.ButterKnife.inject(this);
        initFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.fl_home, mFragmentList.get(0)).commit();

        //底部按键监听
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton rb = (RadioButton) radioGroup.findViewById(i);
                int newCheckedIndex = radioGroup.indexOfChild(rb);
                if (newCheckedIndex != lastCheckedIndex) {
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    Fragment showFragment = mFragmentList.get(newCheckedIndex);
                    Fragment hideFragment = mFragmentList.get(lastCheckedIndex);
                    if (showFragment.isAdded()) {
                        transaction.show(showFragment).hide(hideFragment);
                    } else {
                        transaction.add(R.id.fl_home, showFragment).hide(hideFragment);
                    }
                    transaction.commit();
                    lastCheckedIndex = newCheckedIndex;
                }
            }
        });
    }

    private void initFragment() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new SelectFragment());
        mFragmentList.add(new CategoryFragment());
        mFragmentList.add(new ProfileFragment());
    }
}
